// pages/i/order-detail.js
const BizGoodsOrderService = require('../../services/bizOrder');
import drawQrcode from 'weapp-qrcode';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,
    loading: true,
    error: null,
    orderData: null,
    defaultTicket: null,
    otherTickets: [],
    showQrcodeModal: false,
    currentTicket: null,
    showComplaintDialog: false,
    complaintContent: '',
    submittingComplaint: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.order_id) {
      this.setData({
        orderId: options.order_id
      });
      this.loadData();
    } else {
      this.setData({
        loading: false,
        error: '订单ID不能为空'
      });
    }
  },

  /**
   * 加载订单数据
   */
  async loadData() {
    if (!this.data.orderId) {
      return;
    }

    this.setData({
      loading: true,
      error: null
    });

    try {
      const result = await BizGoodsOrderService.getOrderDetail(this.data.orderId);

      if (result.success) {
        // 处理核销码数据
        const tickets = result.data.tickets || [];
        const now = Math.floor(Date.now() / 1000);
        
        // 找到未使用且未过期的核销码作为默认显示
        const validTickets = tickets.filter(ticket => 
          ticket.status === 0 && ticket.expired_at > now
        );
        
        let defaultTicket = null;
        let otherTickets = [];
        
        if (validTickets.length > 0) {
          defaultTicket = validTickets[0];
          otherTickets = validTickets.slice(1);
        } else {
          // 如果没有有效的核销码，显示第一个未使用的
          const unusedTickets = tickets.filter(ticket => ticket.status == 0);
          if (unusedTickets.length > 0) {
            defaultTicket = unusedTickets[0];
            otherTickets = unusedTickets.slice(1);
          }
        }


        this.setData({
          loading: false,
          orderData: result.data,
          defaultTicket: defaultTicket,
          otherTickets: otherTickets
        }, function () {
          // 生成默认核销码的二维码
          if (defaultTicket) {
            this.generateQrcode(defaultTicket.code, 'defaultQrcode');
          }
        });
      } else {
        this.setData({
          loading: false,
          error: result.message
        });
      }
    } catch (error) {
      this.setData({
        loading: false,
        error: error.message || '加载失败'
      });
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  },

  /**
   * 复制核销码
   */
  copyTicketCode(e) {
    const code = e.currentTarget.dataset.code;
    wx.setClipboardData({
      data: code,
      success: () => {
        wx.showToast({
          title: '核销码已复制',
          icon: 'success'
        });
      }
    });
  },

  /**
   * 预览二维码
   */
  previewQrcode(e) {
    const code = e.currentTarget.dataset.code;
    // 这里可以添加二维码预览功能
    wx.showToast({
      title: '核销码：' + code,
      icon: 'none'
    });
  },

  /**
   * 生成二维码
   */
  generateQrcode(text, canvasId) {
    const ops = {
      width: canvasId === 'modalQrcode' ? 200 : 150,
      height: canvasId === 'modalQrcode' ? 200 : 150,
      canvasId: canvasId,
      text: "http://ruian-store.nai8.me/v1/biz-goods-ticket/check?code="+text,
    };
     
    drawQrcode(ops).then(() => {
      console.log('二维码生成成功');
    }).catch((err) => {
      console.error('二维码生成失败:', err);
    });
  },

  /**
   * 显示核销码二维码弹窗
   */
  showTicketQrcode(e) {
    const ticket = e.currentTarget.dataset.ticket;
    this.setData({
      showQrcodeModal: true,
      currentTicket: ticket
    }, function () {
      // 生成弹窗中的二维码
      this.generateQrcode(ticket.code, 'modalQrcode');
    });
  },

  /**
   * 隐藏核销码二维码弹窗
   */
  hideQrcodeModal() {
    this.setData({
      showQrcodeModal: false,
      currentTicket: null
    });
  },

  handleComplaint() {
    this.setData({
      showComplaintDialog: true,
      complaintContent: ''
    });
  },
  async submitComplaint() {
    if (!this.data.complaintContent.trim()) {
      wx.showToast({ title: '请输入投诉内容', icon: 'none' });
      return;
    }
    this.setData({ submittingComplaint: true });
    const res = await BizGoodsOrderService.complaint(this.data.orderId, this.data.complaintContent);
    this.setData({ submittingComplaint: false });
    if (res.success) {
      wx.showToast({ title: '投诉提交成功', icon: 'success' });
      this.setData({ showComplaintDialog: false });
    } else {
      wx.showToast({ title: res.message, icon: 'none' });
    }
  },
  onComplaintDialogClose() {
    this.setData({ showComplaintDialog: false });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    
    return {
      title: '订单详情1',
      path: `/pages/i/order-detail?id=${this.data.orderId}`
    };
  }
})